<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">WebVTT API</h1>
        <p class="text-gray-300 text-lg">
          Web 视频文本轨道格式，用于字幕、标题和其他文本信息
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300">
          您的浏览器不支持 Text Track API。此功能需要现代浏览器支持。
        </p>
      </div>

      <template v-if="isSupported">
        <!-- 视频播放器 -->
        <div class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-video text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">视频播放器</h2>
          </div>

          <div class="space-y-6">
            <!-- 视频容器 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <video
                ref="videoElement"
                controls
                crossorigin="anonymous"
                class="w-full rounded-lg bg-black"
                @loadedmetadata="onVideoLoaded"
                @timeupdate="onTimeUpdate"
                @play="onPlay"
                @pause="onPause"
              >
                <source :src="currentVideo.url" :type="currentVideo.type">
                您的浏览器不支持 video 标签。
              </video>

              <div class="mt-4 grid grid-cols-2 md:grid-cols-4 gap-2 text-sm">
                <div class="bg-gray-900 rounded p-2 text-center">
                  <div class="text-gray-400">当前时间</div>
                  <div class="text-white font-semibold">{{ formatTime(currentTime) }}</div>
                </div>
                <div class="bg-gray-900 rounded p-2 text-center">
                  <div class="text-gray-400">总时长</div>
                  <div class="text-white font-semibold">{{ formatTime(duration) }}</div>
                </div>
                <div class="bg-gray-900 rounded p-2 text-center">
                  <div class="text-gray-400">播放状态</div>
                  <div class="text-white font-semibold">{{ isPlaying ? '播放中' : '已暂停' }}</div>
                </div>
                <div class="bg-gray-900 rounded p-2 text-center">
                  <div class="text-gray-400">文本轨道</div>
                  <div class="text-white font-semibold">{{ textTracks.length }} 条</div>
                </div>
              </div>
            </div>

            <!-- 视频选择 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">示例视频</h3>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                <button
                  v-for="video in demoVideos"
                  :key="video.name"
                  @click="loadVideo(video)"
                  :class="[
                    currentVideo.name === video.name ? 'bg-tech-accent' : 'bg-gray-700 hover:bg-gray-600',
                    'text-white px-4 py-3 rounded-lg transition-colors text-left'
                  ]"
                >
                  <div class="font-semibold">{{ video.name }}</div>
                  <div class="text-xs text-gray-300 mt-1">{{ video.description }}</div>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 字幕管理 -->
        <div class="tech-card mb-8">
          <div class="flex items-center mb-6">
            <i class="i-carbon-text-annotation-toggle text-3xl text-tech-accent mr-3"></i>
            <h2 class="text-2xl font-semibold text-white">字幕管理</h2>
          </div>

          <div class="space-y-6">
            <!-- 添加字幕轨道 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">添加字幕轨道</h3>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label class="block text-gray-300 mb-2 text-sm">轨道类型:</label>
                  <select
                    v-model="newTrack.kind"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                    <option value="subtitles">字幕 (Subtitles)</option>
                    <option value="captions">标题 (Captions)</option>
                    <option value="descriptions">描述 (Descriptions)</option>
                    <option value="chapters">章节 (Chapters)</option>
                    <option value="metadata">元数据 (Metadata)</option>
                  </select>
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">语言:</label>
                  <select
                    v-model="newTrack.srclang"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                    <option value="zh-CN">中文简体</option>
                    <option value="zh-TW">中文繁体</option>
                    <option value="en">英语</option>
                    <option value="ja">日语</option>
                    <option value="ko">韩语</option>
                  </select>
                </div>

                <div>
                  <label class="block text-gray-300 mb-2 text-sm">标签:</label>
                  <input
                    v-model="newTrack.label"
                    type="text"
                    placeholder="例如: 中文字幕"
                    class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm focus:border-tech-accent outline-none"
                  >
                </div>

                <div class="flex items-end">
                  <label class="flex items-center text-gray-300">
                    <input
                      v-model="newTrack.default"
                      type="checkbox"
                      class="mr-2"
                    >
                    设为默认
                  </label>
                </div>
              </div>

              <div class="mb-4">
                <label class="block text-gray-300 mb-2 text-sm">WebVTT 内容:</label>
                <textarea
                  v-model="newTrack.content"
                  rows="8"
                  placeholder="WEBVTT&#10;&#10;00:00:00.000 --> 00:00:05.000&#10;这是第一句字幕"
                  class="w-full bg-gray-700 text-white border border-gray-600 rounded-lg px-3 py-2 text-sm font-mono focus:border-tech-accent outline-none"
                ></textarea>
              </div>

              <div class="flex gap-3">
                <button
                  @click="addTrack"
                  :disabled="!newTrack.content"
                  class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <i class="i-carbon-add mr-2"></i>
                  添加轨道
                </button>

                <button
                  @click="loadSampleVTT"
                  class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors"
                >
                  <i class="i-carbon-document mr-2"></i>
                  加载示例
                </button>

                <button
                  @click="clearTrackForm"
                  class="bg-gray-700 hover:bg-gray-600 text-white px-6 py-3 rounded-lg transition-colors"
                >
                  <i class="i-carbon-clean mr-2"></i>
                  清空
                </button>
              </div>
            </div>

            <!-- 已添加的轨道 -->
            <div class="bg-gray-800 rounded-lg p-6">
              <h3 class="text-white font-semibold mb-4">已添加的轨道 ({{ textTracks.length }})</h3>

              <div v-if="textTracks.length === 0" class="text-center py-8 text-gray-400">
                暂无文本轨道
              </div>

              <div v-else class="space-y-3">
                <div
                  v-for="(track, index) in textTracks"
                  :key="index"
                  class="bg-gray-900 rounded-lg p-4"
                >
                  <div class="flex items-start justify-between mb-3">
                    <div class="flex-1">
                      <h4 class="text-white font-semibold">{{ track.label || '未命名轨道' }}</h4>
                      <div class="text-gray-400 text-sm mt-1">
                        {{ getTrackKindText(track.kind) }} · {{ track.language }}
                      </div>
                    </div>
                    <div class="flex items-center gap-2">
                      <span
                        :class="[
                          track.mode === 'showing' ? 'bg-green-600' :
                          track.mode === 'hidden' ? 'bg-yellow-600' :
                          'bg-gray-600',
                          'px-2 py-1 rounded text-xs text-white'
                        ]"
                      >
                        {{ getTrackModeText(track.mode) }}
                      </span>
                    </div>
                  </div>

                  <div class="flex gap-2">
                    <button
                      @click="toggleTrack(track)"
                      class="tech-button text-sm"
                    >
                      <i class="i-carbon-view mr-1"></i>
                      {{ track.mode === 'showing' ? '隐藏' : '显示' }}
                    </button>

                    <button
                      @click="showTrackCues(track)"
                      class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-2 rounded-lg transition-colors text-sm"
                    >
                      <i class="i-carbon-list mr-1"></i>
                      查看 Cues ({{ track.cues?.length || 0 }})
                    </button>

                    <button
                      @click="downloadTrack(track)"
                      class="bg-green-600 hover:bg-green-700 text-white px-3 py-2 rounded-lg transition-colors text-sm"
                    >
                      <i class="i-carbon-download mr-1"></i>
                      下载
                    </button>

                    <button
                      @click="removeTrack(index)"
                      class="bg-red-600 hover:bg-red-700 text-white px-3 py-2 rounded-lg transition-colors text-sm"
                    >
                      <i class="i-carbon-trash-can mr-1"></i>
                      删除
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 活动 Cues -->
        <div v-if="activeCues.length > 0" class="tech-card mb-8">
          <h2 class="text-2xl font-semibold mb-6 text-white">当前活动 Cues</h2>

          <div class="space-y-3">
            <div
              v-for="(cue, index) in activeCues"
              :key="index"
              class="bg-gray-800 rounded-lg p-4"
            >
              <div class="flex items-start justify-between mb-2">
                <div class="text-white font-semibold text-lg">{{ cue.text }}</div>
                <div class="text-gray-400 text-sm">
                  {{ formatTime(cue.startTime) }} → {{ formatTime(cue.endTime) }}
                </div>
              </div>
              <div v-if="cue.id" class="text-gray-500 text-xs">ID: {{ cue.id }}</div>
            </div>
          </div>
        </div>

        <!-- WebVTT 示例 -->
        <div class="tech-card mb-8">
          <h2 class="text-2xl font-semibold mb-6 text-white">WebVTT 格式示例</h2>

          <div class="space-y-4">
            <div
              v-for="example in vttExamples"
              :key="example.title"
              class="bg-gray-800 rounded-lg p-6"
            >
              <h3 class="text-white font-semibold mb-3">{{ example.title }}</h3>
              <p class="text-gray-400 text-sm mb-3">{{ example.description }}</p>
              <pre class="bg-gray-900 rounded p-4 text-sm text-gray-300 font-mono overflow-x-auto">{{ example.content }}</pre>
              <button
                @click="useExample(example.content)"
                class="mt-3 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
              >
                <i class="i-carbon-copy mr-1"></i>
                使用此示例
              </button>
            </div>
          </div>
        </div>
      </template>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>所有现代浏览器都支持 WebVTT 和 Text Track API</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">核心 API</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">HTMLTrackElement</code> - track 元素接口</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">TextTrack</code> - 文本轨道对象</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">TextTrackCue</code> - 文本轨道提示点</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">VTTCue</code> - WebVTT 提示点</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">video.textTracks</code> - 获取文本轨道列表</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">轨道类型</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li><strong>subtitles:</strong> 字幕（对话翻译）</li>
              <li><strong>captions:</strong> 标题（对话、音效等完整文本）</li>
              <li><strong>descriptions:</strong> 视频内容的文字描述</li>
              <li><strong>chapters:</strong> 章节标题</li>
              <li><strong>metadata:</strong> 元数据（脚本使用）</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">WebVTT 基本格式</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
WEBVTT

<span class="text-gray-500">NOTE 这是一个注释</span>

<span class="text-green-400">1</span>
<span class="text-blue-400">00:00:00.000 --> 00:00:05.000</span>
这是第一句字幕

<span class="text-green-400">2</span>
<span class="text-blue-400">00:00:05.500 --> 00:00:10.000</span>
这是第二句字幕</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">WebVTT 高级特性</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-gray-500">/* 样式 */</span>
WEBVTT

STYLE
::cue {
  background-color: rgba(0,0,0,0.8);
  color: white;
}

<span class="text-gray-500">/* 位置和对齐 */</span>
<span class="text-blue-400">00:00:00.000 --> 00:00:05.000 align:start line:0%</span>
顶部左对齐字幕

<span class="text-gray-500">/* 语音和类 */</span>
<span class="text-blue-400">00:00:05.000 --> 00:00:10.000</span>
<span class="text-yellow-400">&lt;v 张三&gt;&lt;c.important&gt;重要信息&lt;/c&gt;&lt;/v&gt;</span></pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>视频字幕和翻译</li>
              <li>无障碍访问（听障用户）</li>
              <li>视频章节导航</li>
              <li>视频元数据同步</li>
              <li>视频内容搜索和索引</li>
              <li>互动视频和弹幕</li>
              <li>教育视频注释</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">基本用法</h4>
            <pre class="bg-gray-800 p-4 rounded text-sm overflow-x-auto">
<span class="text-gray-500">// HTML 中添加 track</span>
<span class="text-yellow-400">&lt;video controls&gt;</span>
  <span class="text-yellow-400">&lt;source src="video.mp4" type="video/mp4"&gt;</span>
  <span class="text-yellow-400">&lt;track src="subtitles-zh.vtt" kind="subtitles" 
         srclang="zh-CN" label="中文" default&gt;</span>
<span class="text-yellow-400">&lt;/video&gt;</span>

<span class="text-gray-500">// JavaScript 添加 track</span>
<span class="text-blue-400">const</span> video = document.querySelector(<span class="text-green-400">'video'</span>);
<span class="text-blue-400">const</span> track = video.addTextTrack(<span class="text-green-400">'subtitles'</span>, <span class="text-green-400">'中文'</span>, <span class="text-green-400">'zh-CN'</span>);
track.mode = <span class="text-green-400">'showing'</span>;

<span class="text-gray-500">// 添加 cue</span>
<span class="text-blue-400">const</span> cue = <span class="text-blue-400">new</span> VTTCue(<span class="text-orange-400">0</span>, <span class="text-orange-400">5</span>, <span class="text-green-400">'字幕文本'</span>);
track.addCue(cue);</pre>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">最佳实践</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>提供多语言字幕选项</li>
              <li>确保字幕时间精确同步</li>
              <li>使用合适的文本长度（避免过长）</li>
              <li>为听障用户提供完整标题</li>
              <li>使用章节标记帮助导航</li>
              <li>测试不同浏览器的显示效果</li>
              <li>提供字幕下载功能</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'

// 类型定义
interface DemoVideo {
  name: string
  description: string
  url: string
  type: string
}

interface NewTrackData {
  kind: TextTrackKind
  srclang: string
  label: string
  default: boolean
  content: string
}

interface VTTExample {
  title: string
  description: string
  content: string
}

// 响应式状态
const isSupported = ref(true)
const videoElement = ref<HTMLVideoElement | null>(null)
const currentTime = ref(0)
const duration = ref(0)
const isPlaying = ref(false)

// 示例视频
const demoVideos: DemoVideo[] = [
  {
    name: '示例视频 1',
    description: 'Big Buck Bunny',
    url: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
    type: 'video/mp4'
  },
  {
    name: '示例视频 2',
    description: 'Sintel',
    url: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4',
    type: 'video/mp4'
  }
]

const currentVideo = ref(demoVideos[0])

// 新轨道数据
const newTrack = ref<NewTrackData>({
  kind: 'subtitles',
  srclang: 'zh-CN',
  label: '中文字幕',
  default: true,
  content: ''
})

// 文本轨道
const textTracks = ref<TextTrack[]>([])
const activeCues = ref<VTTCue[]>([])

// WebVTT 示例
const vttExamples: VTTExample[] = [
  {
    title: '基础字幕',
    description: '简单的字幕格式',
    content: `WEBVTT

1
00:00:00.000 --> 00:00:05.000
欢迎来到 WebVTT 演示

2
00:00:05.500 --> 00:00:10.000
这是一个基础的字幕示例

3
00:00:10.500 --> 00:00:15.000
字幕可以帮助理解视频内容`
  },
  {
    title: '带样式的字幕',
    description: '使用样式和格式',
    content: `WEBVTT

STYLE
::cue {
  background-color: rgba(0,0,0,0.8);
  color: white;
  font-size: 18px;
}

1
00:00:00.000 --> 00:00:05.000
<b>粗体文本</b>和<i>斜体文本</i>

2
00:00:05.000 --> 00:00:10.000
<c.highlight>高亮文本</c>`
  },
  {
    title: '位置和对齐',
    description: '控制字幕位置',
    content: `WEBVTT

1
00:00:00.000 --> 00:00:05.000 align:start line:0%
顶部左对齐

2
00:00:05.000 --> 00:00:10.000 align:center line:50%
居中显示

3
00:00:10.000 --> 00:00:15.000 align:end line:100%
底部右对齐`
  },
  {
    title: '说话者标识',
    description: '标识不同说话者',
    content: `WEBVTT

1
00:00:00.000 --> 00:00:05.000
<v 张三>你好，我是张三</v>

2
00:00:05.000 --> 00:00:10.000
<v 李四>很高兴见到你，我是李四</v>

3
00:00:10.000 --> 00:00:15.000
<v 张三>让我们开始吧</v>`
  },
  {
    title: '章节标记',
    description: '视频章节导航',
    content: `WEBVTT

1
00:00:00.000 --> 00:01:00.000
第一章：介绍

2
00:01:00.000 --> 00:03:00.000
第二章：主要内容

3
00:03:00.000 --> 00:05:00.000
第三章：总结`
  }
]

// 计算属性
const textTracksComputed = computed(() => {
  if (!videoElement.value) return []
  return Array.from(videoElement.value.textTracks)
})

// 初始化
onMounted(() => {
  isSupported.value = !!(HTMLVideoElement && 'textTracks' in HTMLVideoElement.prototype)
})

// 视频加载完成
const onVideoLoaded = () => {
  if (videoElement.value) {
    duration.value = videoElement.value.duration
    updateTextTracks()
  }
}

// 时间更新
const onTimeUpdate = () => {
  if (videoElement.value) {
    currentTime.value = videoElement.value.currentTime
    updateActiveCues()
  }
}

// 播放
const onPlay = () => {
  isPlaying.value = true
}

// 暂停
const onPause = () => {
  isPlaying.value = false
}

// 加载视频
const loadVideo = (video: DemoVideo) => {
  currentVideo.value = video
  if (videoElement.value) {
    videoElement.value.load()
  }
}

// 更新文本轨道列表
const updateTextTracks = () => {
  if (!videoElement.value) return
  textTracks.value = Array.from(videoElement.value.textTracks)
}

// 添加轨道
const addTrack = () => {
  if (!videoElement.value || !newTrack.value.content) return

  try {
    const track = videoElement.value.addTextTrack(
      newTrack.value.kind,
      newTrack.value.label,
      newTrack.value.srclang
    )

    track.mode = newTrack.value.default ? 'showing' : 'hidden'

    // 解析 VTT 内容
    parseVTTContent(track, newTrack.value.content)

    updateTextTracks()
    clearTrackForm()
  } catch (error) {
    console.error('添加轨道失败:', error)
    alert('添加轨道失败，请检查 VTT 格式是否正确')
  }
}

// 解析 VTT 内容
const parseVTTContent = (track: TextTrack, content: string) => {
  const lines = content.split('\n')
  let i = 0

  // 跳过 WEBVTT 头部
  while (i < lines.length && !lines[i].includes('-->')) {
    i++
  }

  while (i < lines.length) {
    const line = lines[i].trim()

    if (line.includes('-->')) {
      const [timeRange] = line.split(/\s+/)
      const times = timeRange.split('-->')
      
      if (times.length === 2) {
        const startTime = parseTimeString(times[0].trim())
        const endTime = parseTimeString(times[1].trim())
        
        i++
        let text = ''
        
        while (i < lines.length && lines[i].trim() !== '') {
          text += lines[i] + '\n'
          i++
        }

        if (startTime !== null && endTime !== null) {
          const cue = new VTTCue(startTime, endTime, text.trim())
          track.addCue(cue)
        }
      }
    }
    
    i++
  }
}

// 解析时间字符串
const parseTimeString = (timeStr: string): number | null => {
  const parts = timeStr.split(':')
  
  if (parts.length === 3) {
    const hours = parseInt(parts[0])
    const minutes = parseInt(parts[1])
    const seconds = parseFloat(parts[2])
    return hours * 3600 + minutes * 60 + seconds
  } else if (parts.length === 2) {
    const minutes = parseInt(parts[0])
    const seconds = parseFloat(parts[1])
    return minutes * 60 + seconds
  }
  
  return null
}

// 切换轨道显示
const toggleTrack = (track: TextTrack) => {
  track.mode = track.mode === 'showing' ? 'hidden' : 'showing'
  updateTextTracks()
}

// 显示轨道 Cues
const showTrackCues = (track: TextTrack) => {
  if (!track.cues) {
    alert('此轨道没有 cues')
    return
  }

  const cues = Array.from(track.cues as TextTrackCueList)
  const cueInfo = cues.map((cue, index) => {
    const vttCue = cue as VTTCue
    return `${index + 1}. [${formatTime(vttCue.startTime)} → ${formatTime(vttCue.endTime)}]\n${vttCue.text}`
  }).join('\n\n')

  alert(`共 ${cues.length} 个 Cues:\n\n${cueInfo}`)
}

// 下载轨道
const downloadTrack = (track: TextTrack) => {
  if (!track.cues) return

  let vttContent = 'WEBVTT\n\n'
  
  const cues = Array.from(track.cues as TextTrackCueList)
  cues.forEach((cue, index) => {
    const vttCue = cue as VTTCue
    vttContent += `${index + 1}\n`
    vttContent += `${formatVTTTime(vttCue.startTime)} --> ${formatVTTTime(vttCue.endTime)}\n`
    vttContent += `${vttCue.text}\n\n`
  })

  const blob = new Blob([vttContent], { type: 'text/vtt' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${track.label || 'subtitle'}.vtt`
  a.click()
  URL.revokeObjectURL(url)
}

// 移除轨道
const removeTrack = (index: number) => {
  const track = textTracks.value[index]
  if (track && videoElement.value) {
    // TextTrack 无法直接移除，需要通过 DOM 操作
    const trackElements = videoElement.value.querySelectorAll('track')
    if (trackElements[index]) {
      trackElements[index].remove()
    }
    updateTextTracks()
  }
}

// 更新活动 Cues
const updateActiveCues = () => {
  const cues: VTTCue[] = []
  
  textTracks.value.forEach(track => {
    if (track.mode === 'showing' && track.activeCues) {
      Array.from(track.activeCues).forEach(cue => {
        cues.push(cue as VTTCue)
      })
    }
  })
  
  activeCues.value = cues
}

// 加载示例 VTT
const loadSampleVTT = () => {
  newTrack.value.content = vttExamples[0].content
}

// 使用示例
const useExample = (content: string) => {
  newTrack.value.content = content
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 清空表单
const clearTrackForm = () => {
  newTrack.value = {
    kind: 'subtitles',
    srclang: 'zh-CN',
    label: '中文字幕',
    default: true,
    content: ''
  }
}

// 格式化时间
const formatTime = (seconds: number): string => {
  if (!isFinite(seconds)) return '00:00'
  
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  
  if (h > 0) {
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  }
  return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}

// 格式化 VTT 时间
const formatVTTTime = (seconds: number): string => {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  const ms = Math.floor((s % 1) * 1000)
  
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${Math.floor(s).toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`
}

// 获取轨道类型文本
const getTrackKindText = (kind: TextTrackKind): string => {
  const kinds: Record<TextTrackKind, string> = {
    subtitles: '字幕',
    captions: '标题',
    descriptions: '描述',
    chapters: '章节',
    metadata: '元数据'
  }
  return kinds[kind] || kind
}

// 获取轨道模式文本
const getTrackModeText = (mode: TextTrackMode): string => {
  const modes: Record<TextTrackMode, string> = {
    showing: '显示中',
    hidden: '已隐藏',
    disabled: '已禁用'
  }
  return modes[mode] || mode
}
</script>

<style scoped>
video {
  max-height: 500px;
}
</style>

